package yelmor.comm100.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import yelmor.comm100.domain.CoUser;
import yelmor.comm100.domain.OfMessageArchive;
import yelmor.comm100.repository.CoUserRepository;
import yelmor.comm100.repository.OfMessageArchiveRepository;
import yelmor.comm100.util.SecurityUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yel on 2016/5/6.
 */
@Controller
public class ServiceController {


  @Autowired
  private CoUserRepository coUserRepository;

  @Autowired
  private OfMessageArchiveRepository ofMessageArchiveRepository;

  @Value("${openfire.host}")
  private String openfireHost;

  @RequestMapping(path="/user/serviceManage/{serviceName}")
  public String messageHistory(@PathVariable String serviceName, Model model) {
    String curUserName = SecurityUtil.getCurrentUserName();
    if(curUserName.equals("anonymousUser")) {
      model.addAttribute("notLogin", true);
    } else {
      model.addAttribute("userName", curUserName);
      CoUser coUser = coUserRepository.findOne(curUserName);
      model.addAttribute("coUser", coUser);
      String serviceJid = serviceName + "-service-" + coUser.getSiteCode() + "@" + openfireHost;
      List<OfMessageArchive> messageArchives = ofMessageArchiveRepository.findByFromJIDOrToJID(serviceJid, serviceJid);
      System.out.println("get " + messageArchives.size());
      for(OfMessageArchive messageArchive: messageArchives) {
        System.out.println(messageArchive.toString());
      }
      model.addAttribute("serviceName", serviceName);
      model.addAttribute("messageArchives", messageArchives);
    }
    return "serviceMessageHistory";
  }

}
